import React, { Suspense, useState, useEffect } from "react";
import { Routes, Route, useNavigate, useParams, useSearchParams, useLocation } from "react-router-dom"
import routes from "./routes";
import { Mask, DotLoading, Toast } from 'antd-mobile'
import store from "../store"
import action from "../store/action"


const Element = function Element(props) {
    const { component: Component, meta: { title }, path } = props;
    let [isShow, setIsShow] = useState(false);
    document.title = title || "知乎日报webApp";
    const navigate = useNavigate(),
        params = useParams(),
        [search] = useSearchParams(),
        location = useLocation();

    const check = ["/personal", "/store", "/update"];
    let { base } = store.getState();
    // debugger
    // console.log("isShow", isShow, path)

    //就是网慢点时候会先显示person组件，为什么明明默认是false
    let baseobj;
    useEffect(() => {
        try {
            (async () => {
                if (!base?.info && check.includes(path)) {
                    baseobj = await action.base.queryUserInfoAsync();
                    // console.log("baseobj", baseobj)
                    if (!baseobj?.info) {
                        Toast.show({ icon: "fail", content: "请先登录" })
                        navigate(`/login?to=${path}`, { replace: true });
                        setIsShow(true)
                        return;
                    }
                    store.dispatch(baseobj)
                    setIsShow(true)
                } else {
                    setIsShow(true)
                }
            })()
        } catch (error) {
        };
    })


    return (isShow ? <Component navigate={navigate} params={params} search={search} location={location} />
        : <Mask visible={true}><DotLoading color='white' /></Mask>)
}

export default function RouterView() {
    return <Suspense fallback={<Mask visible={true}><DotLoading color='white' /></Mask>}>
        <Routes>
            {routes.map((item) => {
                return <Route key={item.name} path={item.path} element={<Element {...item} />}></Route>
            })}
        </Routes>
    </Suspense>
}
